package com.example.secondhandspringboot.utils;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.aigc.generation.models.QwenParam;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.MessageManager;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;
import io.reactivex.Flowable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class AIUtil {

    private static final String systemContent = "你是校林二手交易圈网站的一个智能AI助手，可以来解答用户的一些问题，你的名字叫小林。";

    public static String callWithMessage(String userContent, String apiKey)
            throws NoApiKeyException, ApiException, InputRequiredException {
        Constants.apiKey=apiKey;
        Generation gen = new Generation();

        Message systemMsg = Message.builder().role(Role.SYSTEM.getValue()).content(systemContent).build();
        Message userMsg = Message.builder().role(Role.USER.getValue()).content(userContent).build();

        List<Message> messages = new ArrayList<>();

        messages.add(systemMsg);
        messages.add(userMsg);
        QwenParam param =
                QwenParam.builder().model(Generation.Models.QWEN_TURBO).messages(messages)
                        .resultFormat(QwenParam.ResultFormat.MESSAGE)
                        .topP(0.8).enableSearch(true)
                        .incrementalOutput(true)
                        .build();
        Flowable<GenerationResult> result = gen.streamCall(param);
        StringBuilder fullContent = new StringBuilder();
        result.blockingForEach(message -> {
            fullContent.append(message.getOutput().getChoices().get(0).getMessage().getContent());
            System.out.println(message.getOutput().getChoices().get(0).getMessage());
        });
        return fullContent.toString();
//        return result.getOutput().getChoices().get(0).getMessage().getContent();
    }
}
